<template>
    <div class="lazyImgBox">
        <div v-show="show" class="lazyImg" :style="style"></div>
        <div v-show="replaceShow" class="lazyImg" :style="replaceStyle"></div>
    </div>
</template>
<script>
export default {

    name: 'lazyImg',

    props: ['src', 'replace'],

    data: function() {
        return {
            style: '',
            show: false,
            replaceStyle: '',
            replaceShow: false
        }
    },

    created: function() {
        //console.log('created lazyImg', this.src);
        // need，First Do not activated 
        this.iconImg();
    },

    activated: function() {
        //console.log('activated lazyImg', this.src);
        this.iconImg();
    },

    methods: {
        imgStyle(src) {
            let str = '';
            if (src) {
                str = 'background-image:url(' + src + ')';
            }
            return str;
        },

        iconImg() {
            this.show = false;
            this.replaceShow = false;
            if (this.src) {
                let tthis = this,
                    img = new Image();
                img.src = this.src;
                img.onload = function() {
                    tthis.style = tthis.imgStyle(tthis.src);
                    tthis.show = true;
                    tthis.replaceImg();
                };
                img.onerror = function() {
                    console.log('The image could not be loaded.', img.src);
                }
            }
        },

        replaceImg() {
            if (this.replace) {
                let tthis = this,
                    img = new Image();
                img.src = this.replace;
                img.onload = function() {
                    setTimeout(function() {
                        tthis.show = false;
                    }, 1000)
                };
                img.onerror = function() {
                    console.log('The image could not be loaded.', img.replace);
                }
                tthis.replaceStyle = tthis.imgStyle(tthis.replace);
                tthis.replaceShow = true;
            }
        }
    }
}

</script>
<style scoped>
.lazyImgBox {
    width: 100%;
    height: 100%;
    position: absolute;
}

.lazyImg {
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    position: absolute;
}

</style>
